package cn.com.joyplus.wechat.listener;

import cn.com.joyplus.wechat.exceptions.WechatEventListenerException;
import cn.com.joyplus.wechat.model.*;
import cn.com.joyplus.wechat.service.WechatCommonApiService;
import cn.com.joyplus.wechat.service.WechatUserApiService;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.StringWriter;
import java.util.List;

/**
 * Created by 王灏川(wangrs@qq.com) on 2017/8/11 0011.
 *
 * 处理用户发给公众号的文本消息
 * <xml><ToUserName><![CDATA[gh_baaf1686e313]]></ToUserName>
 * <FromUserName><![CDATA[obWde08iJXKTezCCnERt39XphoAI]]></FromUserName>
 * <CreateTime>1501970434</CreateTime>
 * <MsgType><![CDATA[text]]></MsgType>
 * <Content><![CDATA[你好！]]></Content>
 * <MsgId>6450913894026416873</MsgId>
 * </xml>
 */
@Component
public class TextMessageListener implements IMsgListener {
    private static final Logger logger = LoggerFactory.getLogger(TextMessageListener.class);

    @Autowired
    WechatUserApiService wechatUserApiService;

    @Autowired
    WechatCommonApiService wechatCommonApiService;

    @Autowired
    WechatContext wechatContext;

    @Value("${msg.template.answer}")
    private String msgTemplateAnswerId;

    @Override
    public String process(WechatEvent event) throws WechatEventListenerException {
        if (null == event.getContent()) return null;

        String content = event.getContent().trim();

        if (content.equalsIgnoreCase("你好")) {
            return buildMsg(event.getFromUserName(),"你好，需要什么帮助吗?");
        }

        if (content.equalsIgnoreCase("git")) {
            return buildMsg(event.getFromUserName(),"http://git.oschina.net/happysearch/wechat-demo");
        }

        if (content.equalsIgnoreCase("help") || content.equals("?")  || content.equals("？")) {
            return buildHelpMsg(event);
        }
        if (content.equalsIgnoreCase("lau")) {
            return buildUserListMsg(event);
        }

        if (content.startsWith("@")) {
            return buildTemplateUserMsg(event);
        }

        return null;
    }

    /**
     * 被动回复消息，用户输入的help或？后，回复帮助信息
     * @param event
     * @return
     * @throws WechatEventListenerException
     */
    private String buildHelpMsg(WechatEvent event) throws WechatEventListenerException {
        return buildMsg(event.getFromUserName(),
                "使用帮助:\n" +
                        "* lau\n" +
                        "    列出所有用户\n" +
                        "* git\n" +
                        "    源代码下载地址\n" +
                        "* @用户名 消息内容\n" +
                        "    发送模板消息给指定用户"
        );
    }
    /**
     * 被动回复消息，用户输入lau命令后，调用微信Api接口获取所有当前关注用户的详情并回复给用户
     * @param event
     * @return
     * @throws WechatEventListenerException
     */
    private String buildUserListMsg(WechatEvent event) throws WechatEventListenerException {
        StringBuilder content = new StringBuilder();
        try {
            wechatUserApiService.getAllUsers().forEach((WechatUser u) -> {
                if (content.length() > 0) content.append("\n");
                content.append(String.format("%s,%s", u.getNickname(), u.getRemark()));
            });

        } catch (Exception e) {
            throw new WechatEventListenerException(e.getMessage());
        }

        content.insert(0, "所有关注用户:\n");
        return buildMsg(event.getFromUserName(), content.toString());

    }

    /**
     * 被动回复消息"success"，同时调用微信Api接口发送模板消息给选中用户
     * @param event
     * @return
     * @throws WechatEventListenerException
     */
    private String buildTemplateUserMsg(WechatEvent event) throws WechatEventListenerException {
        String content = event.getContent().trim();
        int firstSpaceChar = content.indexOf(" ");
        if (firstSpaceChar < 0) return null;
        String userName = content.substring(1, firstSpaceChar);
        List<WechatUser> wechatUsers = null;

        try {
            wechatUsers = wechatUserApiService.getAllUsers();
        } catch (Exception e) {
            throw new WechatEventListenerException(e.getMessage());
        }
        String fromUserName = null;
        String toUserOpenId = null;

        if (null != wechatUsers) {
            for (WechatUser u : wechatUsers) {
                if (userName.equals(u.getNickname()) || userName.equals(u.getRemark())) {
                    toUserOpenId = u.getOpenid();
                }
                if (event.getFromUserName().equals(u.getOpenid())) {
                    fromUserName = (null == u.getRemark() || u.getRemark().trim().length() == 0) ? u.getNickname() : u.getRemark();
                }
                if (fromUserName != null && toUserOpenId != null) {
                    TemplateMessage tm = new TemplateMessage(msgTemplateAnswerId, u.getOpenid());
                    tm.addFirstTemplateData(content.substring(firstSpaceChar + 1));
                    tm.addRemarkTemplateData(String.format("发送者:%s", fromUserName));
                    try {
                        wechatCommonApiService.callCommonApi("sendTemplateMsg", tm);
                    } catch (Exception e) {
                        throw new WechatEventListenerException(e.getMessage());
                    }
                }
            }
        }
        return "success";
    }

    public String buildMsg(String toUser, String content) throws WechatEventListenerException {

        if (wechatContext.getMyOpenId() == null) return "";
        try {
            TextReplyMessage textReplyMessage = new TextReplyMessage();
            textReplyMessage.setContent(content);
            textReplyMessage.setMsgType("text");
            textReplyMessage.setFromUserName(wechatContext.getMyOpenId());
            textReplyMessage.setToUserName(toUser);
            StringWriter writer = new StringWriter();
            new XmlMapper().writeValue(writer, textReplyMessage);
            return writer.toString();
        } catch (Exception e) {
            throw new WechatEventListenerException("创建文本消息失败");
        }
    }


}